import type { dataTS } from "./type"

type initStateTS = {
    datalist: Array<dataTS>
}

interface actionTS {
    type: string,
    payload: any
}


//定义一个状态对象 管理共享数据
let initState: initStateTS = {
    datalist: [
        { id: 1001, typeId: 1, title: '王明阳', ms: '王明阳描述', img: '/img/01.jpg', sub: true, collect: true },
        { id: 1002, typeId: 1, title: '庆余年2', ms: '庆余年2描述', img: '/img/02.jpg', sub: false, collect: false },
        { id: 1003, typeId: 1, title: '温柔又美好的友谊', ms: '温柔又美好的友谊描述', img: '/img/03.jpg', sub: false, collect: false },
        { id: 2001, typeId: 2, title: '后羿射日', ms: '后羿射日描述', img: '/img/04.jpg', sub: false, collect: false },
        { id: 2002, typeId: 2, title: '三体', ms: '三体描述', img: '/img/21.jpg', sub: false, collect: false },
        { id: 2003, typeId: 2, title: '哈利波特', ms: '哈利波特描述', img: '/img/22.jpg', sub: false, collect: false },
        { id: 3001, typeId: 3, title: '旧事理', ms: '旧事理描述', img: '/img/23.jpg', sub: false, collect: false },
        { id: 3002, typeId: 3, title: '一路繁花相送', ms: '一路繁花相送描述', img: '/img/31.jpg', sub: false, collect: false },
        { id: 3003, typeId: 3, title: '鲁滨逊漂流记', ms: '鲁滨逊漂流记描述', img: '/img/41.jpg', sub: false, collect: false },
    ]
}

//创建一个修改状态的函数
function reducer(oldState: initStateTS, action: actionTS) {
    //深拷贝数据
    let newlist = JSON.parse(JSON.stringify(oldState))
    let { type, payload } = action

    //收藏切换
    if (type == 'change_collect') {
        newlist.datalist.forEach((item: dataTS) => {
            if (item.id == payload) {
                item.collect = !item.collect
            }
        })
    }

    //订阅切换
    if (type == 'change_sub') {
        newlist.datalist.forEach((item: dataTS) => {
            if (item.id == payload) {
                item.sub = !item.sub
            }
        })
    }



    return newlist
}

//导出
export { reducer, initState }